package com.xm.queue.util;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程执行者
 * @author wang-xiaoming
 *
 */
public class TaskExecutor {
	private static ExecutorService execute;
	
	private TaskExecutor() {}
	
	/**
	 * 获取线程池实例
	 * @return 返回线程池单例
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static ExecutorService getInstance(){
		if(execute == null){
			SynchronousQueue executorQueue = new SynchronousQueue<>();
			// 单个线程线程池，只有一个线程的线程池，阻塞队列使用的是LinkedBlockingQueue,若有多余的任务提交到线程池中，则会被暂存到阻塞队列，待空闲时再去执行。按照先入先出的顺序执行任务。
			// 阿里编程规范，不允许使用Executors去创建，而是通过ThreadPoolExecutor的方式，这样的处理方式让写的同学更加明确线程池的运行规则，规避资源耗尽的风险
//			execute = Executors.newCachedThreadPool();
			execute = new ThreadPoolExecutor(0, 2147483647, MyUtil.DURATION, MyUtil.SECONDS, executorQueue);
		}
//		System.out.println("当前线程：" + execute.toString());
		return execute;
	}
	
	/**
	 * 执行线程
	 * @param runnable 线程任务
	 */
	public static void execute(Runnable runnable){
		execute = getInstance();
		execute.execute(runnable);
		System.out.println("执行线程：" + execute.toString());
	}

	/**
	 * 销毁线程池
	 */
	public static void shutdown(){
		if(execute != null){
			System.out.println("当前线程已销毁：" + execute.toString());
			execute.shutdown();
			execute = null;
		}
	}
	
}
